// 画像统计信息页面交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化进度条动画
    initProgressBars();

    // 初始化图表
    initCharts();

    // 绑定科目点击事件
    bindSubjectClicks();

    // 绑定导出功能
    bindExportFunctionality();

    // 初始化趋势分析
    initTrendAnalysis();
});

// 初始化进度条动画
function initProgressBars() {
    const progressBars = document.querySelectorAll('.mastery-progress-bar');
    progressBars.forEach(bar => {
        const width = bar.style.width;
        bar.style.width = '0';
        setTimeout(() => {
            bar.style.width = width;
        }, 300);
    });
}

// 初始化图表
function initCharts() {
    initMasteryDistributionChart();
    initStatusDistributionChart();
    initSubjectComparisonChart();
}

// 初始化掌握度分布图表
function initMasteryDistributionChart() {
    const ctx = document.getElementById('masteryDistributionChart');
    if (!ctx) return;

    // 这里可以使用Chart.js创建饼图
    // 示例代码：
    /*
    const masteryData = JSON.parse(document.getElementById('masteryData').textContent);

    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: masteryData.map(item => item.range),
            datasets: [{
                data: masteryData.map(item => item.count),
                backgroundColor: [
                    '#28a745',
                    '#17a2b8',
                    '#ffc107',
                    '#dc3545'
                ]
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    */
}

// 初始化状态分布图表
function initStatusDistributionChart() {
    const ctx = document.getElementById('statusDistributionChart');
    if (!ctx) return;

    // 类似的Chart.js代码
}

// 初始化科目对比图表
function initSubjectComparisonChart() {
    const ctx = document.getElementById('subjectComparisonChart');
    if (!ctx) return;

    // 类似的Chart.js代码
}

// 绑定科目点击事件
function bindSubjectClicks() {
    const subjectItems = document.querySelectorAll('.subject-item');
    subjectItems.forEach(item => {
        item.addEventListener('click', function() {
            const subjectName = this.dataset.subjectName;
            if (subjectName) {
                // 跳转到科目详情页面
                window.location.href = `/analysis/subject/${this.dataset.subjectId}/`;
            }
        });
    });
}

// 绑定导出功能
function bindExportFunctionality() {
    const exportBtn = document.getElementById('exportStatistics');
    if (exportBtn) {
        exportBtn.addEventListener('click', exportStatisticsData);
    }
}

// 导出统计数据
function exportStatisticsData() {
    const statisticsData = {
        exportTime: new Date().toISOString(),
        overview: {
            totalKnowledgePoints: document.querySelector('[data-stat="total-points"]').textContent,
            avgMastery: document.querySelector('[data-stat="avg-mastery"]').textContent
        },
        masteryDistribution: getMasteryDistributionData(),
        statusDistribution: getStatusDistributionData(),
        subjectStats: getSubjectStatsData(),
        trendAnalysis: getTrendAnalysisData()
    };

    const dataStr = JSON.stringify(statisticsData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `profile-statistics-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    showNotification('画像统计数据导出成功！', 'success');
}

// 获取掌握度分布数据
function getMasteryDistributionData() {
    const items = document.querySelectorAll('.mastery-item');
    const data = [];

    items.forEach(item => {
        const range = item.querySelector('.mastery-range').textContent;
        const count = item.querySelector('.mastery-count').textContent;
        const percentage = item.querySelector('.mastery-percentage').textContent;

        data.push({
            range: range,
            count: parseInt(count),
            percentage: parseFloat(percentage)
        });
    });

    return data;
}

// 获取状态分布数据
function getStatusDistributionData() {
    const items = document.querySelectorAll('.status-item');
    const data = [];

    items.forEach(item => {
        const label = item.querySelector('.status-label').textContent;
        const value = item.querySelector('.status-value').textContent;

        data.push({
            status: label,
            count: parseInt(value)
        });
    });

    return data;
}

// 获取科目统计数据
function getSubjectStatsData() {
    const items = document.querySelectorAll('.subject-item');
    const data = [];

    items.forEach(item => {
        const name = item.querySelector('.subject-name').textContent;
        const count = item.querySelector('.subject-count').textContent;
        const mastery = item.querySelector('.subject-mastery').textContent;

        data.push({
            subject: name,
            totalPoints: parseInt(count),
            avgMastery: parseFloat(mastery)
        });
    });

    return data;
}

// 获取趋势分析数据
function getTrendAnalysisData() {
    const items = document.querySelectorAll('.trend-item');
    const data = {};

    items.forEach(item => {
        const label = item.querySelector('.trend-label').textContent;
        const value = item.querySelector('.trend-value').textContent;

        if (label.includes('提升')) data.improving = parseInt(value);
        else if (label.includes('下降')) data.declining = parseInt(value);
        else if (label.includes('稳定')) data.stable = parseInt(value);
    });

    return data;
}

// 初始化趋势分析
function initTrendAnalysis() {
    const trendItems = document.querySelectorAll('.trend-item');

    trendItems.forEach(item => {
        const value = parseInt(item.querySelector('.trend-value').textContent);
        const total = parseInt(document.querySelector('[data-stat="total-points"]').textContent);
        const percentage = total > 0 ? (value / total * 100).toFixed(1) : 0;

        // 添加百分比显示
        const percentageElement = document.createElement('div');
        percentageElement.className = 'trend-percentage text-muted small';
        percentageElement.textContent = `${percentage}%`;
        item.appendChild(percentageElement);
    });
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 初始化所有功能
function initializeAll() {
    initProgressBars();
    initCharts();
    bindSubjectClicks();
    bindExportFunctionality();
    initTrendAnalysis();
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAll);
} else {
    initializeAll();
}